package com.example.papercut.controller;

import com.example.papercut.entity.TemplateRating;
import com.example.papercut.service.TemplateRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/ratings")
public class TemplateRatingController {

    private final TemplateRatingService ratingService;

    @Autowired
    public TemplateRatingController(TemplateRatingService ratingService) {
        this.ratingService = ratingService;
    }

    /**
     * POST /api/ratings
     * 提交/更新用户对模板的评分和评论
     * 
     * @param rating 包含 user.id, papercut.id, ratingValue, reviewText
     */
    @PostMapping
    public ResponseEntity<String> submitRating(@RequestBody TemplateRating rating) {
        // 实际项目中，user.id 应该从 Session 或 JWT 中获取，而非 RequestBody
        try {
            // 假设 rating 对象的 user.id 和 papercut.id 已经被正确设置
            ratingService.submitOrUpdateRating(rating);
            return ResponseEntity.ok("评分提交/更新成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("提交失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误: " + e.getMessage());
        }
    }

    /**
     * GET /api/ratings/papercut/10/average
     * 获取指定模板的平均评分
     */
    @GetMapping("/papercut/{papercutId}/average")
    public ResponseEntity<Double> getAverageRating(@PathVariable Integer papercutId) {
        Double avgRating = ratingService.getAverageRating(papercutId);
        return ResponseEntity.ok(avgRating);
    }

    /**
     * GET /api/ratings/papercut/10
     * 获取指定模板的所有评论列表
     */
    @GetMapping("/papercut/{papercutId}")
    public ResponseEntity<List<TemplateRating>> getComments(@PathVariable Integer papercutId) {
        List<TemplateRating> comments = ratingService.getRatingsByPapercutId(papercutId);
        return ResponseEntity.ok(comments);
    }

    /**
 * GET /api/ratings/user/{userId}
 * 3.2: 获取用户评分历史
 * 🚨 对应前端的 getUserRatings API
 */
@GetMapping("/user/{userId}") // 完整的路径是 /api/ratings/user/{userId}
public ResponseEntity<List<TemplateRating>> getUserRatings(@PathVariable Integer userId) {
    // ⚠️ 假设 Service 层有相应的实现
    List<TemplateRating> ratings = ratingService.getRatingsByUserId(userId); 
    return ResponseEntity.ok(ratings);
}
}